import React, { PureComponent } from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import moment from 'moment';
import { Select, Input, Button, DatePicker, Cascader, Checkbox, message } from 'antd';
import PTable from "../../../components/Pro/PTable";

// import PSelect from "../../../components/Pro/PSelect";
import {
  enterprisePerResumeForSearchPage, //获取人才搜索
  enterpriseSaveResumeFromSearchPage,//获取收藏简历
  getDistrictData,//获得地区
  getDictInformation,//字典数据
} from "../../../services/api";

const { Option } = Select;
const { RangePicker } = DatePicker;
const CheckboxGroup = Checkbox.Group;
const dateFormat = 'YYYY-MM-DD';

// @connect(state => ({
//   monitor: state.monitor,
// }))
export default class BrainPeople extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      /**
       * 抽屉需要
       */
      number: 0,
      forceUpdate: false,
      pageParm: {
        pageSize: '10',
        pageNumber: '1',
        keyword: '',
        startTall: '',
        endTall: '',
        startWork: '',
        endWork: '',
        startUpdateTime: '',
        endUpdateTime: '',
        startAge: '',
        endAge: '',
        areas: [],//地区
        educations: [],//学历集合
      },

      keyword: '',
      startTall: '',
      endTall: '',
      startWork: '',
      endWork: '',
      startTime: null,
      endTime: null,
      startAge: '',
      endAge: '',
      areas: [],//地区
      arera_Val: [],//区域选中值
      start: false,
      end: false,
      educations: [],//学历集合
      educationList: [],//搜索学历数组

      plainOptions:[],//学历集合
      valueArray:[],//学历的值
    };

  }

  componentDidMount = () => {
    this.getReceiveResume();//获取人才搜索
    this.getDistrict();//省市区
    this.getAllType();//字典
  };
  //省市区
  getDistrict = () => {
    getDistrictData().then((data) => {
      console.log('省市区data:', data);
      const areas = data.data.map((val) => {
        return {
          value: val.regionId,
          label: val.regionName,
          children: val.childs.map((valChild) => {
            return {
              value: valChild.regionId,
              label: valChild.regionName,
              children: valChild.childs.map((valChildChild) => {
                return {
                  value: valChildChild.regionId,
                  label: valChildChild.regionName,
                };
              })
            };
          })
        };
      }
      );
      //console.log('areas:'+JSON.stringify(areas));
      this.setState({
        areas,
      });
    });
  };
  //获得公共信息
  getAllType = () => {
    getDictInformation({ codeTypes: ['education'] }).then((res) => {
      console.log('人才搜索-需要所有字典数据-res:', res);
      //判断获取数据是否为空
      if (res.data) {
        const allTypeData = res.data;
        this.setState({
          educationList: allTypeData.education,//学历
        });
        this.renderEducationMore();
      }
    });
  };
  //获取任务列表
  getReceiveResume = () => {
    const pageSize = 10;
    const pageNumber = 1;
    enterprisePerResumeForSearchPage({ pageSize, pageNumber }).then((res) => {
      console.log("获取人才搜索成功:", res);
    }, (err) => {
      console.log("获取人才搜索失败:", err);
    });
  }

  //table 数据变化
  dateTableChange = (data) => {
    console.log(data);
    this.setState({ number: data.total });
  };
  //输入框的书写，求职意向
  inputPositionChange = (e) => {
    console.log(e.target.value.trim());
    this.setState({ keyword: e.target.value.trim() });
  };

  //输入框的书写，开始年龄
  inputStartAgeChange = (e) => {
    console.log(e.target.value.trim());
    this.setState({ startAge: e.target.value.trim() });
  };

  //输入框的书写，结束年龄
  inputEndAgeChange = (e) => {
    console.log(e.target.value.trim());
    this.setState({ endAge: e.target.value.trim() });
    if(parseInt(e.target.value.trim(),10) < parseInt(this.state.startAge,10)){
      message.error("年龄范围不正确");
    }else{
      this.setState({ endAge: e.target.value.trim() });
    }
  };
  //输入框的书写，开始身高
  inputStartTallChange = (e) => {
    console.log(e.target.value.trim());
    this.setState({ startTall: e.target.value.trim() });
  };
  //输入框的书写，结束身高
  inputEndTallChange = (e) => {
    console.log(e.target.value.trim());
    this.setState({ endTall: e.target.value.trim() });
    if(parseInt(e.target.value.trim(),10) < parseInt(this.state.startTall,10)){
      message.error("身高范围不正确");
    }else{
      this.setState({ endTall: e.target.value.trim() });
    }
  };
  //时间选择
  onChangeTime = (date, dateString) => {
    if (dateString[0] !== '') {
      this.setState({
        start: true,
        end: true,
        startTime: dateString[0],
        endTime: dateString[1],
      });
    } else {
      this.setState({
        start: false,
        end: false,
        startTime: '',
        endTime: '',
      });
    }
  };
  //区域选择值
  onChangeDistrict = (value) => {
    console.log('区域选择值', value);
    this.setState({
      arera_Val: value,
    });
  };

  //点击搜索
  search = () => {
    const pageParm = { ...this.state.pageParm };
    if (this.state.start !== false) {
      const startSerachDate = this.state.startTime;
      pageParm.startUpdateTime = startSerachDate;
    } else {
      pageParm.startUpdateTime = '';
    }
    if (this.state.end !== false) {
      const endSerachDate = this.state.endTime;
      pageParm.endUpdateTime = endSerachDate;
    } else {
      pageParm.endUpdateTime = '';
    }
    if (this.state.arera_Val.length !== 0) {
      const areas = this.state.arera_Val[2];
      pageParm.areas = areas;
    } else {
      pageParm.areas = '';
    }

    pageParm.keyword = this.state.keyword;
    pageParm.startAge = this.state.startAge;
    pageParm.endAge = this.state.endAge;
    pageParm.startTall = this.state.startTall;
    pageParm.endTall = this.state.endTall;
    pageParm.endWork = this.state.endWork;
    pageParm.startWork = this.state.startWork;
    pageParm.educations = this.state.educations;
    this.setState({ pageParm });
  };


  //重置
  resetting = () => {
    this.renderEducation();
    this.setState({
      valueArray:[],
      educations: [],//学历集合
      keyword: "",//输入框的值
      startTall: '',
      endTall: "",
      startWork: "",
      endWork: "",
      startTime: "",
      endTime: "",
      start: false,
      end: false,
      startAge: "",
      endAge: "",
      arera_Val: "",
      // areas  : "",

      forceUpdate: true,
    }, () => {
      this.search();
      this.setState({
        forceUpdate: false
      });
    });
  };


  // renderCheckbox = () => {

  //   const plainOptions = ['小学', '初中', '中专', '大专', '本科', '硕士及以上'];

  //   const onCheckChange = (checkedList) => {
  //     console.log(checkedList);
  //     this.setState({
  //       checkedList
  //     });
  //   };
  //   return (
  //     <CheckboxGroup className="checkgroup"
  //       options={plainOptions}
  //       options={this.state.educationList}
  //       value={this.state.checkedList}
  //       onChange={onCheckChange} />
  //   );
  // }

  //checkbox值
  onEducationChange = (checkedValues) => {
    console.log('checked = ', checkedValues.toString());
    this.setState({
      educations: checkedValues.toString(),
      valueArray:checkedValues
    });
  };
  //学历搜索
  renderEducation = () => {
    return this.state.educationList.map((val, key) => {
      return <Checkbox key={key} value={val.codeValue + ""} checked={this.state.checked}>{val.label}</Checkbox>;
    });
  };

  renderEducationMore = () => {
    const wed = [];
    this.state.educationList.map((val, key) => {
      wed.push({
        label: val.label,
        value: val.codeValue
      })
    });
    this.setState({
      plainOptions:wed
    })
  };

  renderColums = () => {
    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '性别',
        dataIndex: 'sexName',
        key: 'sexName',
      },
      {
        title: '年龄',
        render: (age) => (
          <div>
            {age}岁
          </div>
        ),
        dataIndex: 'age',
        key: 'age',
      },
      {
        title: '工作年限',
        dataIndex: 'workTime',
        render: (workTime) => (
          <div>
            {workTime === 0 ? "不满一年" : workTime + "年工作经验"}
          </div>
        ),
        key: 'workTime',
      },
      {
        title: '意向工作',
        dataIndex: 'position',
        key: 'position',
      },
      {
        title: '学历',
        dataIndex: 'educationName',
        key: 'educationName',
      },
      {
        title: '身高',
        dataIndex: 'height',
        render: (height) => (
          <div>
            {height}cm
          </div>
        ),
        key: 'height',
      },
      {
        title: '简历更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
      },
      {
        title: '现居地',
        dataIndex: 'province',
        render: (province, record) => (
          <div>
            {province + "-" + record.city + "-" + record.area}
          </div>
        ),
        key: 'province',
      },
      {
        title: '操作',
        dataIndex: 'f',
        key: 'f',
        render: (text, record) => (
          <Opton>
            <span style={{ color: "#108EE9", cursor: "pointer" }}
              onClick={this.saveResume.bind(this, record.resumeId)}>收藏</span>
          </Opton>
        ),
      }
    ];
    return (
      <PTable
        style={{ marginTop: 20 }}
        columns={columns}
        url="enterprisePerResumeForSearchPage"
        pageParm={this.state.pageParm}
        forceUpdate={this.state.forceUpdate}
        dateChange={this.dateTableChange}
        showTotal={total => `共搜索到${total}条记录`}
      />
    );
  };

  saveResume = (resumeId) => {
    enterpriseSaveResumeFromSearchPage({ resumeId }).then(() => {
      console.log('收藏成功！');
      this.setState({ forceUpdate: false });
    }, (err) => {
      console.log(err);
    });
  };
  //开始工作类型选中值
  handleChangeStartWork = (value) => {
    console.log(`selected ${value}`);
    this.setState({
      startWork: value,
    });
  };
  handleChangeEndWork = (value) => {
    console.log(`selected ${value}`);
    this.setState({
      endWork: value,
    });
  };
  render() {


    return (
      <div>
        {/* 第 1 行 */}
        <Row>
          <span className="label">工作年限:</span>
          <Select defaultValue="11" className="select" value={this.state.startWork} onChange={this.handleChangeStartWork}>
            <Option value="">不限</Option>
            <Option value="0" >应届</Option>
            <Option value="1">一年以上</Option>
            <Option value="2">两年以上</Option>
            <Option value="3">三年以上</Option>
            <Option value="4">四年以上</Option>
            <Option value="5">五年以上</Option>
            <Option value="6">六年以上</Option>
            <Option value="7">七年以上</Option>
            <Option value="8">八年以上</Option>
            <Option value="9">九年以上</Option>
            <Option value="10">十年以上</Option>
          </Select>
          <span className="split">至</span>
          <Select defaultValue="11" className="select" value={this.state.endWork} onChange={this.handleChangeEndWork}>
          <Option value="">不限</Option>
          <Option value="0" >应届</Option>
          <Option value="1">一年以上</Option>
          <Option value="2">两年以上</Option>
          <Option value="3">三年以上</Option>
          <Option value="4">四年以上</Option>
          <Option value="5">五年以上</Option>
          <Option value="6">六年以上</Option>
          <Option value="7">七年以上</Option>
          <Option value="8">八年以上</Option>
          <Option value="9">九年以上</Option>
          <Option value="10">十年以上</Option>
          </Select>
          <span className="label labelshort">年 <span /> 龄:</span>
          <Input
            style={{ marginBottom: "10px", width: 88 }}
            onChange={this.inputStartAgeChange}
            value={this.state.startAge}
          />
          <span className="split">至</span>
          <Input
            style={{ marginBottom: "10px", width: 88 }}
            onChange={this.inputEndAgeChange}
            value={this.state.endAge}
          />
          <span className="label labelshort">身<span />高:</span>
          <Input
            style={{ marginBottom: "10px", width: 108 }}
            onChange={this.inputStartTallChange}
            value={this.state.startTall}
          />
          <span className="split">至</span>
          <Input
            style={{ marginBottom: "10px", width: 108 }}
            onChange={this.inputEndTallChange}
            value={this.state.endTall}
          />
        </Row>

        {/* 第 2 行 */}
        <Row>
          <span className="label">意向职位:</span>
          <Input
            style={{ marginBottom: "10px", width: 214 }}
            onChange={this.inputPositionChange}
            value={this.state.keyword}
          />
          <span className="label labelshort">更新时间:</span>
          <RangePicker
            format={dateFormat}
            onChange={this.onChangeTime}
            style={{ width: 230 }}
            value={[this.state.start ? moment(this.state.startTime, dateFormat) : null, this.state.end ? moment(this.state.endTime, dateFormat) : null]}
          />
          <span className="label labelshort">现居住地:</span>
          <Cascader options={this.state.areas} placeholder="请选择" style={{ width: 250 }} onChange={this.onChangeDistrict} value={this.state.arera_Val} />
        </Row>

        {/* 第 3 行 */}
        <Row>
          <span className="label">学历:</span>
          {/*<Checkbox.Group onChange={this.onEducationChange} className="checkgroup">*/}
            {/*{this.renderEducation()}*/}
          {/*</Checkbox.Group>*/}
          <CheckboxGroup options={this.state.plainOptions} value={this.state.valueArray} onChange={this.onEducationChange}/>
          <div className="btns">
            <Button style={{ marginLeft: 16, marginBottom: '16px' }} type="primary" onClick={this.search}>搜索</Button>
            <Button style={{ marginLeft: 16, marginBottom: '16px' }} onClick={this.resetting}>重置</Button>
          </div>
        </Row>

        {/* table 展示 */}
        <Tip>
          共搜索到 {this.state.number} 条记录
        </Tip>
        {this.renderColums()}
      </div>
    );
  }
}

/************************样式************************/

const Row = style.div`{
  font-size: 14px;
  color: rgba(0,0,0,0.65);
  margin-bottom:16px;
  width:952px;
  .label{
    width:62px;
    margin-right:8px;
    display:inline-block;
    text-align:right;
  }
  .select{
    width:103px;
  }
  .split{
    margin:0 8px;
  }
  .labelshort{
    margin-left:17px;
    >span{
      width:20px;
      display:inline-block;
    }
  }
  .w236{
    width:236px;
  }
  .checkgroup{
    display:inline-block;
  }
  .btns{
    float:right;
  }
}`;
const Tip = style.div`{
    margin:30px 0 16px 0;
    font-size: 12px;
    color: #999999;
    line-height:17px;
}`;

const Opton = style.span`{
  font-size: 12px;
  color: #0F71FF;
  cursor:pointer;
}`;
